package cn.jiyun.filen;

import cn.hutool.jwt.JWTUtil;
import com.alibaba.nacos.api.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * Author 王晨
 * Date 2023/8/22
 */
@Component
@Slf4j
public class MyFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String loginPageUrl="/enter/denl";
        log.info("执行网关");
        ServerHttpRequest request=exchange.getRequest();
        ServerHttpResponse response=exchange.getResponse();
        String path=request.getURI().getPath();
        log.info("url是:{}",path);
        if(path.contains("file")){
            return chain.filter(exchange);
        }

        //鉴权
        if(path.contains(loginPageUrl)){
            log.info("本次访问的是登录页面,直接放行");
            return chain.filter(exchange);
        }else{
            log.info("本次访问的不是登录页面,是其他页面");
            String token=getToken(request);
            //如果token没有值代表之前没有登录过
            if (StringUtils.isBlank(token)){
                log.info("重定向到登录页面");
                //状态 没有权限401
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            }else{
                try {
                 /*   Claims claimsBody= JwtUtil.getClaimsBody(token);
                    int i=JwtUtil.verifyToken(claimsBody);*/
                    boolean verify = JWTUtil.verify(token, "123".getBytes());
                    if(verify){
                        log.info("放行");
                        return chain.filter(exchange);
                    }else{
                        response.setStatusCode(HttpStatus.UNAUTHORIZED);
                        return response.setComplete();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    response.setStatusCode(HttpStatus.UNAUTHORIZED);
                    return response.setComplete();
                }
            }
        }
    }



    @Override
    public int getOrder() {
        return 0;
    }
    private String getToken(ServerHttpRequest request) {
        String token=request.getHeaders().getFirst("token");
        log.info("token:{}",token);
        return token;
    }
}
